package com.example.msi_pc.myweek11;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import java.util.List;

public class RandomNumActivity extends AppCompatActivity {

    RandomNumService binderService;//声明BinderService

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_random_num);

        findViewById(R.id.randomNumBtn).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                //获取BinderService类中的随机数数组
                List number=binderService.getRandomNumber();
                String str="";
                //遍历数组并显示
                for(int i=0;i<number.size();i++){
                    //将获取的号码转为String类型
                    str+=(number.get(i).toString()+" ");
                }
                //获取文本框组件对象
                TextView randomNumTxt= (TextView) findViewById(R.id.randomNumTxt);
                //显示生成的随机号码
                randomNumTxt.setText(str);
            }
        });
    }

    //设置启动Activity时与后台Service进行绑定
    @Override
    protected void onStart(){
        super.onStart();
        //创建启动Service的Intent
        Intent intent=new Intent(this,RandomNumService.class);
        //绑定指定Service
        bindService(intent,conn,BIND_AUTO_CREATE);
    }
    //设置关闭Activity时解除与后台Service的绑定
    @Override
    protected void onStop(){
        super.onStop();
        unbindService(conn);    //解除绑定Service
    }

    //设置与后台Service进行通讯
    private ServiceConnection conn=new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName name, IBinder service){
            //获取后台Service信息
            binderService=((RandomNumService.MyBinder)service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name){

        }
    };
}
